using System;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;

using Office = Microsoft.Office.Core;
using System.IO;
using System.Reflection;
using VB = Microsoft.VisualBasic;

// Office integration attribute. Identifies the startup class for the document. Do not modify.
[assembly:System.ComponentModel.DescriptionAttribute("OfficeStartupClass, Version=1.0, Class=WordObjectModelCS.OfficeCodeBehind")]

namespace WordObjectModelCS
{
  /// <summary>
  /// Contains managed code extensions for the document.
  /// </summary>
  public class OfficeCodeBehind
  {

    /// <summary>
    /// Application object.
    /// </summary>
    internal Word.Application ThisApplication
    {
      get { return thisApplication;}
    }

    /// <summary>
    /// Document object.
    /// </summary>
    internal Word.Document ThisDocument
    {
      get { return thisDocument;}
    }
        
    private Office.CommandBarPopup MenuBarItem;
    // Arbitrary Tag value for new menu item.
    private const string  MENU_TAG = "DEMO_CODE";

    private Word.Application thisApplication = null;
    private Word.Document    thisDocument = null;

    private Word.DocumentEvents2_OpenEventHandler openEvent;
    private Word.DocumentEvents2_CloseEventHandler closeEvent;

    #region Generated initialization code

    /// <summary>
    /// Default constructor.
    /// </summary>
    public OfficeCodeBehind()
    {
    }

    /// <summary>
    /// Required procedure. Do not modify.
    /// </summary>
    /// <param name="application">Application object.</param>
    /// <param name="document">Document object.</param>
    public void _Startup(object application, object document)
    {
      this.thisApplication = application as Word.Application;
      this.thisDocument = document as Word.Document;

      openEvent = new Word.DocumentEvents2_OpenEventHandler (ThisDocument_Open);
      thisDocument.Open += openEvent;

      closeEvent = new Word.DocumentEvents2_CloseEventHandler(ThisDocument_Close);
      ((Word.DocumentEvents2_Event)thisDocument).Close += closeEvent;

      if (ThisDocument.FormsDesign == true)
      {
        thisDocument.ToggleFormsDesign();
        ThisDocument_Open();
      }
    }

    /// <summary>
    /// Required procedure. Do not modify.
    /// </summary>
    public void _Shutdown()
    {
      thisApplication = null;
      thisDocument = null;
    }

    /// <summary>
    /// Finds the control with the specified name in ThisDocument.
    /// </summary>
    /// <param name='name'>Name of the control to find.</param>
    /// <returns>
    /// Returns the specified control, or null if it is not found.
    /// </returns>
    object FindControl(string name)
    {
      return FindControl(name, ThisDocument);
    }
 
    /// <summary>
    /// Returns the control with the specified name in the specified document.
    /// </summary>
    /// <param name='name'>Name of the control to find.</param>
    /// <param name='document'>Document object that contains the control.</param>
    /// <returns>Returns the specified control, or null if it is not found.
    /// </returns>
    object FindControl(string name, Word.Document document)
    {
      try
      {
        foreach (Word.InlineShape shape in document.InlineShapes)
        {
          if (shape.Type == Word.WdInlineShapeType.wdInlineShapeOLEControlObject)
          {
            object oleControl = shape.OLEFormat.Object;
            Type oleControlType = oleControl.GetType();
            string oleControlName = (string) oleControlType.InvokeMember("Name", 
              System.Reflection.BindingFlags.GetProperty, null, oleControl, null);
            if (String.Compare(oleControlName, name, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
            {
              return oleControl;
            }
          }
        }

        foreach (Word.Shape shape in document.Shapes)
        {
          if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoOLEControlObject)
          {
            object oleControl = shape.OLEFormat.Object;
            Type oleControlType = oleControl.GetType();
            string oleControlName = (string) oleControlType.InvokeMember("Name", 
              System.Reflection.BindingFlags.GetProperty, null, oleControl, null);
            if (String.Compare(oleControlName, name, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
            {
              return oleControl;
            }
          }
        }
      }
      catch
      {
        // Returns null if the control is not found.
      }
      return null;
    }

    #endregion

    /// <summary>
    /// Called when the document is opened.
    /// </summary>
    protected void ThisDocument_Open()
    {
      InitMenuBarItems();
    }

    /// <summary>
    /// Called when the document is closed.
    /// </summary>
    protected void ThisDocument_Close()
    {
      RemoveDemoMenuItem();
    }

    
    #region  Handle Command Bars 

    private void InitMenuBarItems() 
    {
      // set { up Command Bars
      Office.CommandBar MainMenuBar;

      try 
      {
        MainMenuBar = ThisApplication.CommandBars["Menu Bar"];
                
        // Attempt to find the existing menu bar item.
        this.MenuBarItem = (Office.CommandBarPopup)MainMenuBar.FindControl(
          Office.MsoControlType.msoControlPopup, Type.Missing, MENU_TAG, Type.Missing, Type.Missing);

        if (this.MenuBarItem == null) 
        {
          this.MenuBarItem = (Office.CommandBarPopup)MainMenuBar.Controls.Add(Office.MsoControlType.msoControlPopup, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
          this.MenuBarItem.Caption = "&Demo Code";
          this.MenuBarItem.Visible = true;
          this.MenuBarItem.Tag = MENU_TAG;

          // Add all the sub menu items.
          HookUpMenuItem("ResetDemoText");
          HookUpMenuItem("CreateNewWindowAndTile", true);
          HookUpMenuItem("SetApplicationCaption");
          HookUpMenuItem("ToggleStatusBar");
          HookUpMenuItem("ListAllDocFilesOnC");
          HookUpMenuItem("ChangeUserName");
          HookUpMenuItem("SpellCheckString");
          HookUpMenuItem("DisplayHelpAbout");
          HookUpMenuItem("MoveAndResizeWindow");
          HookUpMenuItem("LaunchFaxWizard");
          HookUpMenuItem("DisplayFileNewDialog");
          HookUpMenuItem("DisplayUserInfoDialog");
          HookUpMenuItem("DisplayExecuteDialog");
          HookUpMenuItem("HiddenPageSetupDialog");
          HookUpMenuItem("SaveUnsavedDocuments");
          HookUpMenuItem("ShowSelectionType");
          HookUpMenuItem("InsertTextAtSelection");
          HookUpMenuItem("SelectSentence");
          HookUpMenuItem("FormatRangeAndUndo");
          HookUpMenuItem("ManipulateRangeText");
          HookUpMenuItem("CreateBookmarks");
          HookUpMenuItem("ListBookmarks");
          HookUpMenuItem("BookmarkText");
          HookUpMenuItem("FindInSelection");
          HookUpMenuItem("FindInRange");
          HookUpMenuItem("FindInLoopAndFormat");
          HookUpMenuItem("SearchAndReplace");
          HookUpMenuItem("ReplaceAndRestoreSelection");
          HookUpMenuItem("TogglePrintPreview");
          HookUpMenuItem("PrintOutDoc");
          HookUpMenuItem("CreateTable");
        }
      } 
      catch (Exception ex) 
      {
        MessageBox.Show(ex.Message,        
          ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

    private void HookUpMenuItem( string  ProcToCall) 
    {
      HookUpMenuItem(ProcToCall, false);
    }

    private void HookUpMenuItem( string  ProcToCall,  bool BeginNewGroup) 
    {
      Office.CommandBarButton cbb = CreateButton(ProcToCall);
      cbb.Tag = ProcToCall;
      cbb.BeginGroup = BeginNewGroup;
      cbb.Click += new Office._CommandBarButtonEvents_ClickEventHandler(MenuItem_Click);
    }

    private void MenuItem_Click(Office.CommandBarButton Ctrl, ref bool CancelDefault) 
    {
      // Use Reflection, given the name of the procedure, to call the
      // procedure whose name is stored in the button's Tag property.
      // It's ugly, but it works.
      try 
      {
        Type t = typeof(OfficeCodeBehind);
        MethodInfo m = t.GetMethod(Ctrl.Tag);
        m.Invoke(this, null);

      } 
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }

    private Office.CommandBarButton CreateButton(string Caption) 
    {
      Office.CommandBarButton cbb = null;
      try 
      {
        cbb = (Office.CommandBarButton)this.MenuBarItem.Controls.Add(
          Office.MsoControlType.msoControlButton, Type.Missing, 
          Type.Missing, Type.Missing, true);
        cbb.Caption = Caption;
        cbb.Visible = true;
      } 
      catch (Exception ex) 
      {
        MessageBox.Show(ex.Message,        
          ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
      return cbb;
    }
        
    private void RemoveDemoMenuItem() 
    {
      try 
      {
        Office.CommandBar MainMenuBar =  ThisApplication.CommandBars["Menu Bar"];

        // Need to locate the custom menu item again.
        this.MenuBarItem = (Office.CommandBarPopup)MainMenuBar.FindControl(       
          Office.MsoControlType.msoControlPopup, Type.Missing, MENU_TAG, Type.Missing, Type.Missing);
        this.MenuBarItem.Delete(Type.Missing);
      } 
      catch 
      {
        // if there's an error, don't complain.
      }
    }

    #endregion

    public void ResetDemoText() 
    {
      try 
      {
        string  docText = 
          "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam sem. Fusce dignissim. Fusce auctor mauris id nulla. Sed a libero. Nunc ipsum lorem, gravida vitae, imperdiet nec, aliquet a, leo. Phasellus ligula quam, ullamcorper ac, ornare vel, egestas vel, quam. " + Environment.NewLine +
          "In hac habitasse platea dictumst. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. int tellus metus, mattis non, lobortis vitae, faucibus a, purus. Aliquam erat volutpat. Nunc tempor ante eu quam. Vivamus feugiat augue eu risus. " + Environment.NewLine +        
          "Proin ac erat. Maecenas eget nunc in purus pellentesque tincidunt. Nunc justo est, eleifend ut, sollicitudin vel, iaculis ac, sapien. Donec risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed accumsan. Sed tristique. Nulla consequat ornare neque. Phasellus sagittis sem ac mauris. Phasellus orci augue, pellentesque semper, bibendum et, aliquet semper, leo. Suspendisse sit amet sapien non massa dapibus ultricies. Nam orci. Quisque tempor augue sed dolor. Donec malesuada, sem a blandit tincidunt, libero quam dictum wisi, ac adipiscing wisi sem eget mi. " + Environment.NewLine +
          "Ut justo purus, eleifend a, commodo semper, placerat vitae, ligula. Nullam malesuada. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse a diam non augue porttitor bibendum. Etiam imperdiet, erat in consectetuer gravida, lorem justo faucibus augue, vitae iaculis ligula lorem sit amet nunc. Pellentesque pede nulla, dignissim et, luctus a, lacinia in, ipsum. Donec semper. Aliquam vel elit. Phasellus fermentum rutrum nisl. Nulla sit amet tortor. Suspendisse lacinia libero in arcu. Nunc imperdiet nibh nec sem. Sed commodo, odio sed nonummy tristique, tortor mauris aliquam erat, eget blandit wisi urna at turpis.";

        Object start = 0;
        Object end = ThisDocument.Characters.Count;
        Object styleName = "lorem";
        Word.Range rng = ThisDocument.Range(ref start, ref end);
        rng.Text = docText;
        rng.set_Style(ref styleName);
      } 
      catch
      {
        // do nothing
      }
    }


    #region  Application Properties 

    public void CreateNewWindowAndTile() 
    {
      // Create a new window from the active document
      Word.Window wnd =  ThisApplication.ActiveWindow.NewWindow();

      // Tile the two windows
      Object value = Word.WdArrangeStyle.wdTiled;
      ThisApplication.Windows.Arrange(ref value);
    }

    public void SetApplicationCaption() 
    {
      // Change caption in title bar
      ThisApplication.Caption = "My New Caption";
    }

    public void CapsLockOn() 
    {
      MessageBox.Show(ThisApplication.CapsLock.ToString());
    }

    public void DisplayAlerts() 
    {
      // Turn off display of messages and alerts
      try 
      {
        ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
        // Your code runs here without any alerts
        // . . .code doing something here

      } 
      catch (Exception ex)
      {
        // Do something with your exception.

      } 
      finally 
      {
        // Turn alerts on again when done
        ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll;
      }
    }

    public void ToggleStatusBar() 
    {
      // Toggle display of the status bar
      bool bln = ThisApplication.DisplayStatusBar;
      ThisApplication.DisplayStatusBar = !bln;
    }

    public void ListAllDocFilesOnC() 
    {
      try
      {
        ThisApplication.System.Cursor = Word.WdCursorType.wdCursorWait;
        StringWriter  sw = new StringWriter();
        Office.FileSearch fs = ThisApplication.FileSearch;
        fs.FileName = "*.doc";
        fs.LookIn = "C:\\";
        fs.SearchSubFolders = true;
        // Select the defaults, optional in VBA:
        fs.Execute(Office.MsoSortBy.msoSortByFileName, 
          Office.MsoSortOrder.msoSortOrderAscending, true);
        foreach (String str in fs.FoundFiles)
        {
          sw.WriteLine(str);
        } 
        MessageBox.Show(sw.ToString());
      }
      finally
      {
        ThisApplication.System.Cursor = Word.WdCursorType.wdCursorNormal;
      }
    }

    public void ExecutablePath() 
    {
      MessageBox.Show(ThisApplication.Path);
    }

    public void SetAppOptions() 
    {
      // Set various application options
      Word.Options options = ThisApplication.Options;

      options.BackgroundSave = true;
      options.Overtype = true;
      options.UpdateFieldsAtPrint = true;
      options.PrintHiddenText = true;
      options.PrintFieldCodes = true;
    }

    public void ChangeUserName() 
    {
      string  str = ThisApplication.UserName;
      MessageBox.Show(str);

      // Change Username
      ThisApplication.UserName = "Dudley";
      MessageBox.Show(ThisApplication.UserName);
      // Restore original UserName
      ThisApplication.UserName = str;
    }

    public void AppVisibleSafe() 
    {
      try 
      {
        ThisApplication.Visible = false;
        // do whatever it is, invisibly

      } 
      catch (Exception ex)
      {
        // Your exception handler here

      } 
      finally 
      {
        ThisApplication.Visible = true;
      }
    }
    #endregion

    #region  Application Methods 

    public void SpellCheckString() 
    {
      // Checks a specified string for spelling errors
      string  str = "Speling erors here.";

      Object CustomDictionary = Type.Missing;
      Object IgnoreUppercase = Type.Missing;
      Object MainDictionary = Type.Missing;
      Object CustomDictionary2 = Type.Missing;
      Object CustomDictionary3 = Type.Missing;
      Object CustomDictionary4 = Type.Missing;
      Object CustomDictionary5 = Type.Missing;
      Object CustomDictionary6 = Type.Missing;
      Object CustomDictionary7 = Type.Missing;
      Object CustomDictionary8 = Type.Missing;
      Object CustomDictionary9 = Type.Missing;
      Object CustomDictionary10 = Type.Missing;

      // The CheckSpelling method takes a bunch of optional parameters, in VBA:
      if ( ThisApplication.CheckSpelling(str, ref CustomDictionary, 
        ref IgnoreUppercase, ref MainDictionary, ref CustomDictionary2, 
        ref CustomDictionary3, ref CustomDictionary4, ref CustomDictionary5, 
        ref CustomDictionary6, ref CustomDictionary7, ref CustomDictionary8, 
        ref CustomDictionary9, ref CustomDictionary10) ) 
      {
        MessageBox.Show(String.Format("No errors in \"{0}\"", str));
      } 
      else 
      {
        MessageBox.Show(String.Format("\"{0}\" is spelled incorrectly", str));
      }
    }

    public void DisplayHelpAbout() 
    {
      Object value = Word.WdHelpType.wdHelpAbout;
      ThisApplication.Help(ref value);
    }

    public void MoveAndResizeWindow() 
    {
      // None of this will work if the window is maximized or minimized.
      ThisApplication.ActiveWindow.WindowState = Word.WdWindowState.wdWindowStateNormal;

      // Position at upper left corner
      ThisApplication.Move(0, 0);

      // Size to 300 x 600 points
      ThisApplication.Resize(300, 600);
    }

    public void WaysToQuitWord() 
    {
      // Automatically save changes
      Object saveChanges = Word.WdSaveOptions.wdSaveChanges;
      Object originalFormat = Type.Missing;
      Object routeDocument = Type.Missing;
      ThisApplication.Quit(ref saveChanges, 
        ref originalFormat, ref routeDocument);

      // Prompt to save changes
      saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
      originalFormat = Type.Missing;
      routeDocument = Type.Missing;
      ThisApplication.Quit(ref saveChanges, 
        ref originalFormat, ref routeDocument);

      // Quit without saving changes
      saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
      originalFormat = Type.Missing;
      routeDocument = Type.Missing;
      ThisApplication.Quit(ref saveChanges, 
        ref originalFormat, ref routeDocument);
    }

    public void LaunchFaxWizard() 
    {
      ThisApplication.SendFax();
    }

    #endregion

    #region  Dialog Code 

    public void DisplayFileNewDialog() 
    {
      Object timeOut = Type.Missing;

      Word.Dialog dlg;
      dlg = ThisApplication.Dialogs[Word.WdWordDialog.wdDialogFileNew];
      dlg.Show(ref timeOut);
    }

    public void DisplaySpellCheckDialog() 
    {
      Object timeOut = Type.Missing;
      Word.Dialog dlg;
      dlg = ThisApplication.Dialogs
        [Word.WdWordDialog.wdDialogToolsSpellingAndGrammar];
      dlg.Show(ref timeOut);
    }

    public void DisplayUserInfoDialog() 
    {
      Word.Dialog dlg;
      Object timeout = 3000;
      dlg = ThisApplication.Dialogs[Word.WdWordDialog.wdDialogToolsOptionsUserInfo];
      dlg.Display(ref timeout);
    }

    public void DisplayExecuteDialog() 
    {
      Word.Dialog dlg;
      dlg = ThisApplication.Dialogs[Word.WdWordDialog.wdDialogToolsOptionsUserInfo];

      // Wait 10 seconds for results.
      Object timeout = 10000;
      int value = dlg.Display(ref timeout);

      // Did the user press OK?
      if (value == -1) 
      {
        dlg.Execute();
      }
    }

    public void HiddenPageSetupDialog()
    {
      Word.Dialog dlg;
      dlg = ThisApplication.Dialogs[Word.WdWordDialog.wdDialogFilePageSetup];

      VB.Interaction.CallByName(dlg, "PageWidth", VB.CallType.Let, ConvertToInches(3.3));
      VB.Interaction.CallByName(dlg, "PageHeight", VB.CallType.Let, ConvertToInches(6));
      VB.Interaction.CallByName(dlg, "TopMargin", VB.CallType.Let, ConvertToInches(0.72));
      VB.Interaction.CallByName(dlg, "BottomMargin", VB.CallType.Let, ConvertToInches(0.72));
      VB.Interaction.CallByName(dlg, "LeftMargin", VB.CallType.Let, ConvertToInches(0.66));
      VB.Interaction.CallByName(dlg, "RightMargin", VB.CallType.Let, ConvertToInches(0.66));
      VB.Interaction.CallByName(dlg, "Orientation", VB.CallType.Let, Word.WdOrientation.wdOrientPortrait);
      VB.Interaction.CallByName(dlg, "DifferentFirstPage", VB.CallType.Let, false);
      VB.Interaction.CallByName(dlg, "HeaderDistance", VB.CallType.Let, ConvertToInches(0.28));
      // Use the ApplyPropsTo property to determine where
      // the property settings are applied:
      // 0=This Section
      // 1=This Point Forward
      // 2=Selected Sections
      // 3=Selected Text
      // 4=Whole Document
      VB.Interaction.CallByName(dlg, "ApplyPropsTo", VB.CallType.Let, 0);
      dlg.Execute();
    }
    private String ConvertToInches(double value) 
    {
      return String.Format("{0}\"", value);
    }

    #endregion

    #region  Working with Documents 

    public void AddNewDoc() 
    {
      // Create a new document based on Normal.dot
      Object template = Type.Missing;
      Object newTemplate = Type.Missing;
      Object documentType = Type.Missing;
      Object visible = Type.Missing; 

      ThisApplication.Documents.Add( 
        ref template, ref newTemplate, 
        ref documentType, ref visible);

      // Displays the Save dialog box
      ThisApplication.ActiveDocument.Save();
    }

    public void AddNewDocTemplate() 
    {
      // The template is optional. if not supplied,
      // the new document will be based on Normal.dot
      Object template = @"C:\Test\MyTemplate.Dot";
      Object newTemplate = Type.Missing;
      Object documentType = Type.Missing;
      Object visible = Type.Missing; 

      ThisApplication.Documents.Add( 
        ref template, ref newTemplate, 
        ref documentType, ref visible);
    }

    public void OpenDoc() 
    {
      // Open the document read-write
      Object filename = @"C:\Test\MyNewDocument";
      Object confirmConversions = Type.Missing;
      Object readOnly = Type.Missing;
      Object addToRecentFiles = Type.Missing;
      Object passwordDocument = Type.Missing;
      Object passwordTemplate = Type.Missing;
      Object revert = Type.Missing;
      Object writePasswordDocument = Type.Missing;
      Object writePasswordTemplate = Type.Missing;
      Object format = Type.Missing;
      Object encoding = Type.Missing;
      Object visible = Type.Missing;
      Object openConflictDocument = Type.Missing;
      Object openAndRepair  = Type.Missing;
      Object documentDirection = Type.Missing;
      Object noEncodingDialog = Type.Missing;
      
      ThisApplication.Documents.Open(ref filename, ref confirmConversions, 
        ref readOnly, ref addToRecentFiles, ref passwordDocument, 
        ref passwordTemplate, ref revert, ref writePasswordDocument, 
        ref writePasswordTemplate, ref format, ref encoding, ref visible, 
        ref openConflictDocument, ref openAndRepair , ref documentDirection, 
        ref noEncodingDialog);
    }

    public void SaveAllDocs() 
    {
      // Save prompts the user for unsaved changes
      Object noPrompt = Type.Missing;
      Object originalFormat = Type.Missing;

      ThisApplication.Documents.Save(ref noPrompt, ref originalFormat);

      // set NoPrompt to true to save silently
      noPrompt = true;
      ThisApplication.Documents.Save(ref noPrompt, ref originalFormat);
    }

    public void SaveDocument() 
    {
      // Save the active document
      ThisDocument.Save();
      // or
      ThisApplication.ActiveDocument.Save();

      // Save a named document
      Object file = "MyNewDocument.doc";
      ThisApplication.Documents.get_Item(ref file).Save();
      // Save by index number
      file = 1;
      ThisApplication.Documents.get_Item(ref file).Save();
    }

    public void SaveAsDocument() 
    {
      // Save the document. In a real application,
      // you'd want to test to see if the file
      // already exists. This will overwrite any previously 
      // existing documents.
      Object fileName = @"C:\Test\MyNewDocument.doc";
      Object fileFormat = Type.Missing;
      Object lockComments = Type.Missing;
      Object password = Type.Missing;
      Object addToRecentFiles = Type.Missing;
      Object writePassword = Type.Missing;
      Object readOnlyRecommended = Type.Missing;
      Object embedTrueTypeFonts = Type.Missing;
      Object saveNativePictureFormat = Type.Missing;
      Object saveFormsData = Type.Missing;
      Object saveAsAOCELetter = Type.Missing;
      Object encoding = Type.Missing;
      Object insertLineBreaks = Type.Missing;
      Object allowSubstitutions = Type.Missing;
      Object lineEnding = Type.Missing;
      Object addBiDiMarks = Type.Missing;

      ThisDocument.SaveAs(ref fileName, ref fileFormat, ref lockComments, 
        ref password, ref addToRecentFiles, ref writePassword, 
        ref readOnlyRecommended, ref embedTrueTypeFonts, ref saveNativePictureFormat, 
        ref saveFormsData, ref saveAsAOCELetter, ref encoding, 
        ref insertLineBreaks, ref allowSubstitutions, ref lineEnding, 
        ref addBiDiMarks);
    }

    public void CloseAllDocuments() 
    {
      // Closes all open documents. Prompts 
      // the user to save unsaved documents.
      Object saveChanges = Type.Missing;
      Object originalFormat = Type.Missing;
      Object routeDocument = Type.Missing;
      ThisApplication.Documents.Close(ref saveChanges, 
        ref originalFormat, ref routeDocument);

      // Closes all documents: saves with no prompt
      saveChanges = Word.WdSaveOptions.wdSaveChanges;
      originalFormat = Type.Missing;
      routeDocument = Type.Missing;
      ThisApplication.Documents.Close(ref saveChanges, 
        ref originalFormat, ref routeDocument);

      // Closes all documents: does not save any changes
      saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
      originalFormat = Type.Missing;
      routeDocument = Type.Missing;
      ThisApplication.Documents.Close(ref saveChanges, 
        ref originalFormat, ref routeDocument);
    }

    public void CloseDocument() 
    {
      // Close the active document without saving changes
      Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
      Object originalFormat = Type.Missing;
      Object routeDocument = Type.Missing;
      ThisDocument.Close(ref saveChanges, 
        ref originalFormat, ref routeDocument);

      //Close MyNewDocument and save changes without prompting
      Object name = "MyNewDocument.doc";
      saveChanges = Word.WdSaveOptions.wdSaveChanges;
      originalFormat = Type.Missing;
      routeDocument = Type.Missing;

      Word.Document doc = ThisApplication.Documents.get_Item(ref name);
      ThisDocument.Close(ref saveChanges, 
        ref originalFormat, ref routeDocument);
    }

    public void SaveUnsavedDocuments() 
    {
      // Iterate through the Documents collection
      string  str;
      StringWriter  sw = new StringWriter();

      foreach ( Word.Document doc in ThisApplication.Documents)
      {
        if (!doc.Saved ) 
        {
          // Save the document
          doc.Save();
          sw.WriteLine(doc.Name);
        }
      } 

      str = sw.ToString();
      if ( str == string.Empty ) 
      {
        str = "No documents need saving.";
      } 
      MessageBox.Show(str, "SaveUnsavedDocuments");
    }

    #endregion

    #region  Working with the Selection 

    public void ShowSelectionType() 
    {
      string  str;
      switch (ThisApplication.Selection.Type) 
      {
        case Word.WdSelectionType.wdSelectionBlock:
          str = "block";
          break;
        case Word.WdSelectionType.wdSelectionColumn:
          str = "column";
          break;
        case Word.WdSelectionType.wdSelectionFrame:
          str = "frame";
          break;
        case Word.WdSelectionType.wdSelectionInlineShape:
          str = "inline shape";
          break;
        case Word.WdSelectionType.wdSelectionIP:
          str = "insertion point";
          break;
        case Word.WdSelectionType.wdSelectionNormal:
          str = "normal text";
          break;
        case Word.WdSelectionType.wdNoSelection:
          str = "no selection";
          break;
        case Word.WdSelectionType.wdSelectionRow:
          str = "row";
          break;
        default:
          str = "(unknown)";
          break;
      }
      MessageBox.Show(str, "SelectionType");
    }

    public void SelectionMove() 
    {
      Object unit;
      Object count;
      Object extend;

      // Position the the insertion point at the beginning of the document
      unit = Word.WdUnits.wdStory;
      extend = Word.WdMovementType.wdMove;
      ThisApplication.Selection.HomeKey(ref unit, ref extend);

      // Select from the insertion point to the end of the document
      unit = Word.WdUnits.wdStory;
      extend = Word.WdMovementType.wdExtend;
      ThisApplication.Selection.EndKey(ref unit, ref extend);

      // Move the insertion point left 3 characters
      unit = Word.WdUnits.wdCharacter;
      count = 3;
      extend = Word.WdMovementType.wdMove;
      ThisApplication.Selection.MoveLeft(ref unit, ref count, ref extend);

      // Select the 3 words to the right of the insertion point
      unit = Word.WdUnits.wdWord;
      count = 3;
      extend = Word.WdMovementType.wdExtend;
      ThisApplication.Selection.MoveRight(ref unit, ref count, ref extend);

      // Move the insertion point up one line
      unit = Word.WdUnits.wdLine;
      count = 1;
      extend = Word.WdMovementType.wdMove;
      ThisApplication.Selection.MoveUp(ref unit, ref count, ref extend);

      // Select the following 3 paragraphs
      unit = Word.WdUnits.wdParagraph;
      count = 3;
      extend = Word.WdMovementType.wdMove;
      ThisApplication.Selection.MoveDown(ref unit, ref count, ref extend);

      // Use the Move method to move 3 words
      unit = Word.WdUnits.wdWord;
      count = 3;
      ThisApplication.Selection.Move(ref unit, ref count);
    }

    public void InsertTextAtSelection() 
    {
      Word.Selection sln = ThisApplication.Selection;

      // Make sure overtype is turned off
      ThisApplication.Options.Overtype = false;

      
      // Test to see if selection an insertion point
      if (sln.Type == Word.WdSelectionType.wdSelectionIP ) 
      {
        sln.TypeText("Inserting at insertion point. ");
        sln.TypeParagraph();
      } 
      else if (sln.Type == Word.WdSelectionType.wdSelectionNormal ) 
      {
        // Move to start of selection
        if ( ThisApplication.Options.ReplaceSelection ) 
        {
          Object direction = Word.WdCollapseDirection.wdCollapseStart;
          sln.Collapse(ref direction);
        }
        sln.TypeText("Inserting before a text block. ");
        sln.TypeParagraph();
      }
      else
      {
        // Do nothing
      }
    }
    #endregion

    #region  Range Object 
    public void RangeSelectDocument() 
    {
      Object start = Type.Missing;
      Object end = Type.Missing;

      Word.Range rng = ThisDocument.Range(ref start, ref end);
      rng.Select();
      MessageBox.Show("Characters: " + ThisDocument.Characters.Count.ToString());
    }

    public void SelectSentence() 
    {
      Word.Range rng;

      if (ThisDocument.Sentences.Count >= 2 ) 
      {
        // Supply a Start and end value for the Range
        Object start = ThisDocument.Sentences[2].Start;
        Object end = ThisDocument.Sentences[2].End;
        rng = ThisDocument.Range(ref start, ref end);

        // Set the range directly. This gets you the same results.
        rng = ThisDocument.Sentences[2];
        // Select the Range
        rng.Select();
      }
    }

    public void RangeAdjust() 
    {
      // Define a range of 7 characters
      Object start = 0;
      Object end = 7;
      Word.Range rng = ThisDocument.Range(ref start, ref end);

      // Move the starting position 7 characters
      Object unit = Word.WdUnits.wdCharacter;
      Object count = 7;
      rng.MoveStart(ref unit, ref count);

      // Move the ending position 7 characters
      unit = Word.WdUnits.wdCharacter;
      count = 7;
      rng.MoveEnd(ref unit, ref count);

      MessageBox.Show(String.Format("Start: {0}, End: {1}", 
        rng.Start, rng.End), "Range Start and End");
    }

    public void RangeSetRange() 
    {
      Word.Range rng;
      Object start = 0;
      Object end = 7;
      rng = ThisDocument.Range(ref start, ref end);

      // Reset the existing Range
      rng.SetRange(ThisDocument.Sentences[2].Start, ThisDocument.Sentences[5].End);
      rng.Select();
    }

    public void FormatRangeAndUndo() 
    {
      // set the Range to the first paragraph
      Word.Range rng = ThisDocument.Paragraphs[1].Range;
      // Change the formatting
      rng.Font.Size = 14;
      rng.Font.Name = "Arial";
      rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      rng.Select();
      MessageBox.Show("Formatted Range", "FormatRangeAndUndo");

      // Undo the three previous actions
      Object times = 3;
      ThisDocument.Undo(ref times);
      rng.Select();
      MessageBox.Show("Undo 3 actions", "FormatRangeAndUndo");

      // Apply the Normal Indent style
      Object style = "Normal Indent";
      rng.set_Style(ref style);
      rng.Select();
      MessageBox.Show("Normal Indent style applied", "FormatRangeAndUndo");

      // Undo a single action
      times = 1;
      ThisDocument.Undo(ref times);
      rng.Select();
      MessageBox.Show("Undo 1 action", "FormatRangeAndUndo");
    }

    public void TextInsert() 
    {
      // Insert text at insertion point at beginning of document
      string  str = " new Text ";
      Object start = 0;
      Object end = 0;
      Word.Range rng = ThisDocument.Range(ref start, ref end);
      rng.Text = str;
      rng.Select();

      // This will replace the first 12 characters
      start = 0;
      end = 12;
      rng = ThisDocument.Range(ref start, ref end);
      rng.Text = str;
      rng.Select();
    }

    public void RangeCollapse() 
    {
      string  str = " new Text ";
      Word.Range rng = ThisDocument.Paragraphs[1].Range;
      Object direction = Word.WdCollapseDirection.wdCollapseStart;
      rng.Collapse(ref direction);
      rng.Text = str;
      rng.Select();
    }

    public void ManipulateRangeText() 
    {
      // Retrieve contents of first and second paragraphs
      string  str1 = ThisDocument.Paragraphs[1].Range.Text;
      string  str2 = ThisDocument.Paragraphs[2].Range.Text;

      // Swap the paragraphs
      Word.Range rng1 = ThisDocument.Paragraphs[1].Range;
      rng1.Text = str2;

      Word.Range rng2 = ThisDocument.Paragraphs[2].Range;
      rng2.Text = str1;

      // Pause to display the results
      rng1.Select();
      MessageBox.Show(rng1.Text, "ManipulateRangeText");
      rng2.Select();
      MessageBox.Show(rng2.Text, "ManipulateRangeText");

      // Adjust rng1 to de-select last character (para mark)
      Object unit = Word.WdUnits.wdCharacter;
      Object count = -1;
      rng1.MoveEnd(ref unit, ref count);
      // Write new text for paragraph 1
      rng1.Text = "new content for paragraph 1.";

      // Simply write new text to rng2
      rng2.Text = "new content for paragraph 2.";

      // Pause to display the results
      rng1.Select();
      MessageBox.Show(rng1.Text, "ManipulateRangeText");
      rng2.Select();
      MessageBox.Show(rng2.Text, "ManipulateRangeText");

      // Move rng1 to include paragraph mark
      unit = Word.WdUnits.wdCharacter;
      count = 1;
      rng1.MoveEnd(ref unit, ref count);

      // Delete rng2
      // Note that in C#, you must specify 
      // both parameters--it's up to you 
      // to calculate the length of the range.
      unit = Word.WdUnits.wdCharacter;
      count = rng2.Characters.Count;
      rng2.Delete(ref unit, ref count);

      // Restore first paragraph
      rng1.Text = str1;

      // Restore second paragraph
      rng1.InsertAfter(str2);
      rng1.Select();
    }

    #endregion

    #region Bookmarks

    public void CreateBookmarks() 
    {
      Word.Range rng;
      Word.Bookmark bookMk1;
      Word.Bookmark bookMk2;

      // Display Bookmarks
      ThisDocument.ActiveWindow.View.ShowBookmarks = true;

      // Define a Range object as first insertion point
      Object start = 0;
      Object end = 0;
      rng = ThisDocument.Range(ref start, ref end);

      // Add a Bookmark consisting of the Range object
      Object range = rng;
      bookMk1 = ThisDocument.Bookmarks.Add("bookMk1", ref range);

      // Display the bookmark
      MessageBox.Show("bookMk1 Text: " + bookMk1.Range.Text, "CreateBookmarks");

      // Insert text before the first Bookmark
      rng.InsertBefore("**InsertBefore bookMk1**");

      // Show Bookmark text
      MessageBox.Show("bookMk1 Text: " + bookMk1.Range.Text, "CreateBookmarks");

      // Insert text after the first Bookmark
      rng.InsertAfter("**InsertAfter bookMk1**");
      MessageBox.Show("bookMk1 Text: " + bookMk1.Range.Text, "CreateBookmarks");

      // Re-set the Range object to second paragraph
      rng = ThisDocument.Paragraphs[2].Range;

      // Create new Bookmark on paragraph 2
      range = rng;
      bookMk2 = ThisDocument.Bookmarks.Add("bookMk2", ref range);
      MessageBox.Show("bookMk2 Text: " + bookMk2.Range.Text, 
        "bookMk2 set");

      // Insert text before the Bookmark
      rng.InsertBefore("**InsertBefore bookMk2**");
      MessageBox.Show("bookMk2 Text: " + bookMk2.Range.Text, 
        "InsertBefore bookMk2");

      // Insert text after
      rng.InsertAfter("**InsertAfter bookMk2**");
      MessageBox.Show("bookMk2 Text: " + bookMk2.Range.Text, 
        "InsertAfter bookMk2");

      bookMk2.Select();
      MessageBox.Show("bookMk2.Select()", "CreateBookmarks");

      // Delete  Bookmarks
      //bookMk1.Delete()
      //bookMk2.Delete()
    }

    public void ListBookmarks() 
    {
      StringWriter  sw = new StringWriter();

      foreach (Word.Bookmark bmrk in ThisDocument.Bookmarks)
      {
        sw.WriteLine("Name: {0}, Contents: {1}", 
          bmrk.Name, bmrk.Range.Text);
      } 
      MessageBox.Show(sw.ToString(), "Bookmarks and Contents");
    }

    public void BookmarkText() 
    {
      // Create a bookmark on the first paragraph
      Object range = ThisDocument.Paragraphs[1].Range;
      ThisDocument.Bookmarks.Add("bkMark", ref range);

      // Create Range on Bookmark object
      Object name = "bkMark";
      Word.Range rng = ThisDocument.Bookmarks.get_Item(ref name).Range;

      // Replace Range text (this deletes the Bookmark)
      rng.Text = "new Bookmark Text.";

      // Re-create the Bookmark
      range = rng;
      ThisDocument.Bookmarks.Add("bkMark", ref range);

      // Display Bookmark
      ThisDocument.ActiveWindow.View.ShowBookmarks = true;
      name = "bkMark";
      MessageBox.Show(ThisDocument.Bookmarks.
        get_Item(ref name).Range.Text, "BookmarkReplaceText");
    }

    public void ReplaceBookmarkText(string  BookmarkName, string  NewText) 
    {
      if (ThisDocument.Bookmarks.Exists(BookmarkName)) 
      {
        Object name = BookmarkName;
        Word.Range rng = ThisDocument.Bookmarks.get_Item(ref name).Range;
        rng.Text = NewText;
        Object range = rng;
        ThisDocument.Bookmarks.Add(BookmarkName, ref range);
      }
    }

    #endregion

    #region Search and Replace

    public void FindInSelection() 
    {
      // Move selection to beginning of doc
      Object unit = Word.WdUnits.wdStory;
      Object extend = Word.WdMovementType.wdMove;
      ThisApplication.Selection.HomeKey(ref unit, ref extend);

      Word.Find fnd = ThisApplication.Selection.Find;
      fnd.ClearFormatting();

      Object findText = "dolor";
      Object matchCase = Type.Missing;
      Object matchWholeWord = Type.Missing;
      Object matchWildcards = Type.Missing;
      Object matchSoundsLike = Type.Missing;
      Object matchAllWordForms = Type.Missing;
      Object forward = Type.Missing;
      Object wrap = Type.Missing;
      Object format = Type.Missing;
      Object replaceWith = Type.Missing;
      Object replace = Type.Missing;
      Object matchKashida = Type.Missing;
      Object matchDiacritics = Type.Missing;
      Object matchAlefHamza = Type.Missing;
      Object matchControl = Type.Missing;

      if (fnd.Execute(ref findText, ref matchCase, ref matchWholeWord, 
        ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms, 
        ref forward, ref wrap, ref format, ref replaceWith, ref replace, 
        ref matchKashida, ref matchDiacritics, ref matchAlefHamza, 
        ref matchControl))
      {
        MessageBox.Show("Text found.", "FindInSelection");
      } 
      else 
      {
        MessageBox.Show("Text not found.", "FindInSelection");
      }
    }

    public void CriteriaSpecify() 
    {
      // Use Find properties to specify search criteria
      Word.Find fnd = ThisApplication.Selection.Find;

      fnd.ClearFormatting();
      fnd.Forward = true;
      fnd.Wrap = Word.WdFindWrap.wdFindContinue;
      fnd.Text = "ipsum";

      ExecuteFind(fnd);

      // Use Execute method arguments to specify search criteria
      fnd = ThisApplication.Selection.Find;
      fnd.ClearFormatting();

      Object findText = "dolor";
      Object wrap = Word.WdFindWrap.wdFindContinue;
      Object forward = true;
      ExecuteFind(fnd, wrap, forward);
    }

    public void FindInRange() 
    {
      // Set the second paragraph as the search range
      Word.Range rng = ThisDocument.Paragraphs[2].Range;
      Word.Find fnd = rng.Find;

      // Clear existing formatting
      fnd.ClearFormatting();

      // Execute the search
      fnd.Text = "faucibus";
      if (ExecuteFind(fnd))
      {
        MessageBox.Show("Text found.", "FindInRange");
      } 
      else 
      {
        MessageBox.Show("Text not found.", "FindInRange");
      }

      // The word faucibus will be displayed if the
      // search succeeds; paragraph 2 will be displayed
      // if the search fails.
      rng.Select();
    }
  
    public void FindInLoopAndFormat() 
    {
      int intFound = 0;

      Object start = 0;
      Object end = ThisDocument.Characters.Count;
      Word.Range rngDoc = ThisDocument.Range(ref start, ref end);
      Word.Find fnd = rngDoc.Find;

      // Find all instances of the word "lorem" and bold each.
      fnd.ClearFormatting();
      fnd.Forward = true;
      fnd.Text = "lorem";
      ExecuteFind(fnd);
      while (fnd.Found)
      {
        // Set the new font weight and color.
        // Note that each "match" resets
        // the searching range to be the found text.
        rngDoc.Font.Color = Word.WdColor.wdColorRed;
        rngDoc.Font.Bold = 600;
        intFound++;
        ExecuteFind(fnd);
      }
      MessageBox.Show(
        String.Format("lorem found {0} times.", intFound), "FindInLoopAndFormat");
    }
    
    public void SearchAndReplace() 
    {
      // Move selection to beginning of document
      Object unit = Word.WdUnits.wdStory;
      Object extend = Word.WdMovementType.wdMove;
      ThisApplication.Selection.HomeKey(ref unit, ref extend);

      Word.Find fnd = ThisApplication.Selection.Find;
      fnd.ClearFormatting();
      fnd.Text = "Lorem";
      fnd.Replacement.ClearFormatting();
      fnd.Replacement.Text = "Forum";
      ExecuteReplace(fnd);
    }

    public void ReplaceAndRestoreSelection() 
    {
      // Save user's original selection
      Word.Range rngStart = ThisApplication.Selection.Range;

      // Define search range of entire document
      Object start = 0;
      Object end = ThisDocument.Characters.Count;
      Word.Range rngSearch = ThisDocument.Range(ref start, ref end);

      Word.Find fnd = rngSearch.Find;
      fnd.ClearFormatting();
      fnd.Text = "vel";
      fnd.Replacement.ClearFormatting();
      fnd.Replacement.Text = "VELLO";
      ExecuteReplace(fnd);

      // Restore user's original selection
      rngStart.Select();
    }

    #endregion

    #region Printing

    public void TogglePrintPreview() 
    {
      ThisApplication.PrintPreview = !ThisApplication.PrintPreview;
    }

    public void PrintOutDoc() 
    {
      Object background = true;
      Object append = false;
      Object range = Word.WdPrintOutRange.wdPrintCurrentPage;
      Object outputFileName = Type.Missing;
      Object from = Type.Missing;
      Object to = Type.Missing;
      Object item = Word.WdPrintOutItem.wdPrintDocumentContent;
      Object copies = 2;
      Object pages = 1;
      Object pageType = Word.WdPrintOutPages.wdPrintAllPages;
      Object printToFile = false;
      Object collate = Type.Missing;
      Object fileName = Type.Missing;
      Object activePrinterMacGX = Type.Missing;
      Object manualDuplexPrint = Type.Missing;
      Object printZoomColumn = Type.Missing;
      Object printZoomRow = Type.Missing;
      Object printZoomPaperWidth = Type.Missing;
      Object printZoomPaperHeight = Type.Missing;
      
      ThisDocument.PrintOut(ref background, ref append,
        ref range, ref outputFileName, ref from, ref to, 
        ref item, ref copies, ref pages, ref pageType, 
        ref printToFile, ref collate, ref activePrinterMacGX, 
        ref manualDuplexPrint, ref printZoomColumn, 
        ref printZoomRow, ref printZoomPaperWidth, 
        ref printZoomPaperHeight);
    }


    #endregion

    #region Word Tables

    public void CreateTable() 
    {
      // Move to start of document
      Object start = 0;
      Object end = 0;
      Word.Range rng = ThisDocument.Range(ref start, ref end);

      // Insert some text and paragraph marks.
      rng.InsertBefore("Document Statistics");
      rng.Font.Name = "Verdana";
      rng.Font.Size = 16;
      rng.InsertParagraphAfter();
      rng.InsertParagraphAfter();
      rng.SetRange(rng.End, rng.End);

      // Add the table.
      Object defaultTableBehavior = Type.Missing;
      Object autoFitBehavior = Type.Missing;
      Word.Table tbl = rng.Tables.Add(
        ThisDocument.Paragraphs[2].Range, 3, 2, 
        ref defaultTableBehavior, ref autoFitBehavior);

      // Format the table and apply a style
      tbl.Range.Font.Size = 12;
      tbl.Columns.DistributeWidth();
      Object style = "Table Colorful 2";
      tbl.set_Style(ref style);

      // Insert text in cells
      tbl.Cell(1, 1).Range.Text = "Document Property";
      tbl.Cell(1, 2).Range.Text = "value";
      tbl.Cell(2, 1).Range.Text = "Number of Words";
      tbl.Cell(2, 2).Range.Text = 
        ThisDocument.Words.Count.ToString();
      tbl.Cell(3, 1).Range.Text = "Number of Characters";
      tbl.Cell(3, 2).Range.Text = 
        ThisDocument.Characters.Count.ToString();
      tbl.Select();
    }
    #endregion

    #region Find Method Wrappers
    
    private Boolean ExecuteReplace(Word.Find find)
    {
      return ExecuteReplace(find, Word.WdReplace.wdReplaceAll);
    }

    private Boolean ExecuteReplace(Word.Find find, Object replaceOption)
    {
      // Simple wrapper around Find.Execute:
      Object findText = Type.Missing;
      Object matchCase = Type.Missing;
      Object matchWholeWord = Type.Missing;
      Object matchWildcards = Type.Missing;
      Object matchSoundsLike = Type.Missing;
      Object matchAllWordForms = Type.Missing;
      Object forward = Type.Missing;
      Object wrap = Type.Missing;
      Object format = Type.Missing;
      Object replaceWith = Type.Missing;
      Object replace = replaceOption;
      Object matchKashida = Type.Missing;
      Object matchDiacritics = Type.Missing;
      Object matchAlefHamza = Type.Missing;
      Object matchControl = Type.Missing;
      
      return find.Execute(ref findText, ref matchCase, ref matchWholeWord, 
        ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms, 
        ref forward, ref wrap, ref format, ref replaceWith, ref replace, 
        ref matchKashida, ref matchDiacritics, ref matchAlefHamza, 
        ref matchControl);
    }
    
    private Boolean ExecuteFind(Word.Find find)
    {
      return ExecuteFind(find, Type.Missing, Type.Missing);
    }

    private Boolean ExecuteFind(
      Word.Find find, Object wrapFind, Object forwardFind)
    {
      // Simple wrapper around Find.Execute:
      Object findText = Type.Missing;
      Object matchCase = Type.Missing;
      Object matchWholeWord = Type.Missing;
      Object matchWildcards = Type.Missing;
      Object matchSoundsLike = Type.Missing;
      Object matchAllWordForms = Type.Missing;
      Object forward = forwardFind;
      Object wrap = wrapFind;
      Object format = Type.Missing;
      Object replaceWith = Type.Missing;
      Object replace = Type.Missing;
      Object matchKashida = Type.Missing;
      Object matchDiacritics = Type.Missing;
      Object matchAlefHamza = Type.Missing;
      Object matchControl = Type.Missing;
      
      return find.Execute(ref findText, ref matchCase, ref matchWholeWord, 
        ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms, 
        ref forward, ref wrap, ref format, ref replaceWith, ref replace, 
        ref matchKashida, ref matchDiacritics, ref matchAlefHamza, 
        ref matchControl);
    }
    #endregion


  }

}




